<template>
  <div class="data-center-main" ref="dataCenter">
    <div class="top">
      <div
        class="top-part"
        v-for="(item, index) in topList"
        :key="item.id"
        @click="dataSelect(index)"
      >
        <div class="topname">{{ item.name }}</div>
        <div class="topnum" v-show="topchose == index">
          {{ item.status }}{{ total }}
        </div>
      </div>
    </div>
    <div class="bottom">
      <el-form ref="form" :model="queryParams" inline>
        <el-form-item label="设备id">
          <el-input v-model="queryParams.deviceId"></el-input>
        </el-form-item>
        <el-form-item label="在线状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态">
            <el-option
              v-for="item in statusList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="省">
          <el-select
            v-model="queryParams.province"
            filterable
            clearable
            @change="provinceQueryChange"
            placeholder="请选择省份"
          >
            <el-option
              v-for="item in provinceList"
              :key="item.value"
              :label="item.text"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="市">
          <el-select
            v-model="queryParams.city"
            filterable
            clearable
            @change="cityQueryChange"
            placeholder="请选择市"
          >
            <el-option
              v-for="item in cityList"
              :key="item.value"
              :label="item.text"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="区">
          <el-select
            v-model="queryParams.district"
            filterable
            clearable
            @change="regionQueryChange"
            placeholder="请选择市"
          >
            <el-option
              v-for="item in regionList"
              :key="item.value"
              :label="item.text"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="queryForm"
            >检索</el-button
          >
        </el-form-item>
        <el-form-item> </el-form-item>
      </el-form>
      <!-- <div class="operatingBtn">
        <el-button
          type="primary"
          style="font-family: 'HarmonyOS_Sans_SC_Regular'; border: none"
          @click="batchSetLifeCycle"
          >批量设置生命周期</el-button
        >
      </div> -->
      <el-table
        :data="list"
        ref="deviceTable"
        style="height: 80%"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" align="center">
        </el-table-column>
        <el-table-column prop="id" label="id" align="center"> </el-table-column>
        <el-table-column prop="brand" label="品牌型号" align="center">
        </el-table-column>
        <el-table-column prop="deviceId" label="设备id" align="center">
        </el-table-column>
        <el-table-column prop="nickName" label="运维人员名称" align="center">
        </el-table-column>
        <el-table-column prop="openCount" label="设备开门次数" align="center">
        </el-table-column>
        <el-table-column prop="passengerFlow" label="客流量" align="center">
        </el-table-column>
        <el-table-column prop="location" label="设备位置" align="center">
        </el-table-column>
        <el-table-column prop="purity" label="纯净度" align="center">
        </el-table-column>
        <el-table-column prop="temperature" label="设备温度" align="center">
        </el-table-column>
        <el-table-column prop="phase" label="在线状态" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.phase == 0">待分配</div>
            <div v-if="scope.row.phase == 1">待投放</div>
            <div v-if="scope.row.phase == 2">投放中</div>
            <!-- <div v-if="scope.row.phase == 3">带检修</div> -->
          </template>
        </el-table-column>
        <el-table-column
          prop="status"
          label="在线状态"
          align="center"
        >
          <template slot-scope="scope">
            <div>
              <i :class="['status-icon', getColorMap(scope.row.status)]"></i>
              {{ scope.row.status === 1 ? "在线" : "离线" }}
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column label="位置上报" align="center">
            <template slot-scope="scope">
              <el-popover
                placement="top"
                width="200"
                trigger="hover"
                :content="scope.row.location ? scope.row.location.desc : '-'"
              >
                <div class="one-line" slot="reference">
                  {{ scope.row.location ? scope.row.location.desc : "-" }}
                </div>
              </el-popover>
            </template>
          </el-table-column> -->
        <el-table-column prop="positionStatus" label="位置状态" align="center">
        </el-table-column>
        <el-table-column prop="temperature" label="柜温（℃）" align="center">
        </el-table-column>
        <el-table-column prop="openRate" label="开门数（当天）" align="center">
        </el-table-column>
        <el-table-column prop="score" label="客流量（当天）" align="center">
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handlePut(scope.row)"
              >投放</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handledistribution(scope.row)"
              >分配</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
      <!-- 投放渠道弹窗 -->
      <el-dialog
        title="投放设备"
        :visible.sync="putOpen"
        width="900px"
        append-to-body
      >
        <el-form label-width="120px">
          <el-col :span="12">
            <el-form-item label="渠道">
              <el-select v-model="putForm.channelId" placeholder="请选择">
                <el-option
                  v-for="item in channelList"
                  :key="item.id"
                  :label="item.channelName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="sumbitPut">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 分配设备弹窗 -->
      <el-dialog
        title="分配设备"
        :visible.sync="distributionOpen"
        width="900px"
        append-to-body
      >
        <el-form label-width="120px">
          <el-col :span="12">
            <el-form-item label="用户">
              <el-select
                v-model="distributionForm.userName"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in userList"
                  :key="item.nickName"
                  :label="item.nickName"
                  :value="item.nickName"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="distributionDevice"
            >确 定</el-button
          >
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  getDeviceCenterList,
  distributionDevice,
  putDevice,
} from "@/api/device-center/device-center";
import { listPlatformChannel } from "@/api/channel/index";
import { listUser } from "@/api/system/user";
import * as XLSX from "xlsx";
import AllAddress from "@/plugins/data.js";
export default {
  data() {
    return {
      topList: [
        {
          name: "管理中心",
          status: "设备总数：",
          num: "0",
        },
        {
          name: "待分配",
          status: "待分配：",
          num: "0",
        },
        {
          name: "待投放",
          status: "待投放：",
          num: "0",
        },
        {
          name: "投放中",
          status: "投放中：",
          num: "0",
        },
        // {
        //   name: "售后维护",
        //   status: "售后维护：",
        //   num: "0",
        // },
        // {
        //   name: "回收站",
        //   status: "回收站：",
        //   num: "0",
        // },
      ],
      statusList: [
        {
          name: "离线",
          id: 0,
        },
        {
          name: "待机",
          id: 1,
        },
        // {
        //   name: "在线",
        //   id: 2,
        // },
      ],

      topchose: 1,
      rebootResultForm: {
        taskId: "",
      },
      loading: true,
      userList: [],
      channelList: [],
      putForm: {
        deviceId: null,
        channelId: null,
      },
      putOpen: false,
      distributionOpen: false,
      distributionForm: {
        deviceId: null,
        userName: null,
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceId: null,
        orderByColumn: "id",
        status: null,
        province: null,
        city: null,
        district: null,
        isAsc: "asc",
        phase: null,
      },
      form: {
        userId: "",
        twoUserId: "",
        threeUserId: "",
        fourUserId: "",
        fiveUserId: "",
        deviceId: "",
        iccid: "",
      },

      list: [],
      deviceList: [],
      // 分页相关
      total: 0,
      pageNum: 1,
      pageSize: 20,
      projectId: "",
      provinceList: [],
      cityList: [],
      regionList: [],
    };
  },
  mounted() {
    this.projectId = this.$store.state.project.projectId;
    this.init();
    this.getList();
    this.loadPrivinceData();
  },
  filters: {},
  watch: {
    topchose: function () {
      this.topList.map((item, index) => {
        //console.log('adsfasdf', document.getElementsByClassName('top-part')[index].className);
        document.getElementsByClassName("top-part")[index].style.background =
          "#fff";
        document.getElementsByClassName("topname")[index].style.color = "#333";
        document.getElementsByClassName("topnum")[index].style.color = "#333";
      });
      var bg = document.getElementsByClassName("top-part")[this.topchose];
      var tn = document.getElementsByClassName("topname")[this.topchose];
      var nc = document.getElementsByClassName("topnum")[this.topchose];
      bg.style.background = "linear-gradient(to bottom, #5B6BF4, #949FFF)";
      nc.style.color = "#fff";
      tn.style.color = "#fff";
    },
  },

  beforeDestroy() {},
  methods: {
    init() {
      this.loading = true;
      this.topchose = 0;
    },
    getList() {
      this.loading = true;
      const params = this.queryParams;
      getDeviceCenterList(params).then((response) => {
        this.list = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      //this.reset();
    },
    getColorMap(value) {
      // 在线 绿色   不在线红色  未激活黄色
      // emumStatus.ONLINE
      // emumStatus.OFFLINE
      // emumStatus.UNACTIVE

      let color = "c-grey";
      switch (value) {
        case 1:
          color = "c-green";
          break;
        case 0:
          color = "c-red";
          break;
        default:
          break;
      }
      console.log("color", color);

      return color;
    },
    queryForm() {
      console.log(this.queryParams.city);

      if (this.queryParams.province != null) {
        this.queryParams.province =
          this.provinceList[this.queryParams.province].text;
      }

      if (typeof this.queryParams.city === "number") {
        this.queryParams.city = this.cityList[this.queryParams.city].text;
      }
      if (typeof this.queryParams.district == "number") {
        this.queryParams.district =
          this.regionList[this.queryParams.district].text;
      }

      this.getList();
    },
    handlePut(row) {
      this.reset();
      this.putForm.deviceId = row.deviceId;
      this.putOpen = true;
      listPlatformChannel().then((res) => {
        this.channelList = res.rows;
      });
    },

    sumbitPut() {
      console.log("投放参数", this.putForm);
      const params = new FormData();
      params.append("deviceId", this.putForm.deviceId);
      params.append("channelId", this.putForm.channelId);
      putDevice(params)
        .then((response) => {
          if (response.code === 200) {
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1500,
            });
          } else {
            this.$message.error(response.msg);
          }
        })
        .finally(() => {
          this.getList();
          this.putOpen = false;
        });
    },
    handledistribution(row) {
      this.reset();
      this.distributionForm.deviceId = row.deviceId;
      this.distributionOpen = true;
      listUser().then((res) => {
        this.userList = res.rows;
      });
    },

    distributionDevice() {
      console.log("投放参数", this.distributionForm);
      const params = new FormData();
      params.append("deviceId", this.distributionForm.deviceId);
      params.append("userName", this.distributionForm.userName);
      distributionDevice(params)
        .then((response) => {
          if (response.code === 200) {
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1500,
            });
            this.getList();
          } else {
            this.$message.error(response.msg);
          }
        })
        .finally(() => {
          this.getList();
          this.distributionOpen = false;
        });
    },
    reset() {
      this.putForm = {
        deviceId: null,
        channelId: null,
      };
      this.distributionForm = {
        deviceId: null,
        userName: null,
      };
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        deviceId: null,
        orderByColumn: "id",
        status: null,
        province: null,
        city: null,
        district: null,
        isAsc: "asc",
        phase: null,
      };
    },
    cancel() {
      this.putOpen = false;
      this.distributionOpen = false;
    },
    dataSelect(id) {
      this.list = this.listTemp;
      this.topchose = id;
      if (id != 0) {
        var factoryStatuslist = [];
        factoryStatuslist = [];
        this.queryParams.phase = id;
        this.getList();
      } else {
        this.queryParams.phase = null;
        this.getList();
      }
    },
    //选择区
    regionQueryChange(e) {
      this.$forceUpdate();
    },
    //选择市
    cityQueryChange(e) {
      //初始化数据
      this.regionList = [];
      this.queryParams.district = "";
      console.log(this.queryParams.city);

      if (this.queryParams.city != "" || this.queryParams.city === 0) {
        var i = 0;
        this.regionList = AllAddress[this.queryParams.province].city[
          this.queryParams.city
        ].county.map((obj) => {
          return {
            value: i++,
            text: obj.countyName,
          };
        });
      }
      this.$forceUpdate();
    },
    //选择省
    provinceQueryChange(e) {
      //初始化数据
      this.cityList = [];
      this.queryParams.city = "";
      this.regionList = [];
      this.queryParams.district = "";
      if (
        this.queryParams.provinceValue != "" ||
        this.queryParams.provinceValue === 0
      ) {
        //获取市数据
        var i = 0;
        this.cityList = AllAddress[this.queryParams.province].city.map(
          (obj) => {
            return {
              value: i++,
              text: obj.cityName,
            };
          }
        );
      }
      this.$forceUpdate();
    },
    //省份数据加载
    loadPrivinceData() {
      var i = 0;
      this.provinceList = AllAddress.map((obj) => {
        return {
          value: i++,
          text: obj.provinceName,
        };
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.data-center-main {
  background-color: #f3f3f3;
  width: 100%;
  height: calc(100vh - 85px);
  flex-direction: column;
  display: flex;
  padding: 1%;
}

.top {
  height: 15%;
  width: 100%;
  // background-color: #fff;
  margin-bottom: 1%;
  display: flex;
  justify-content: space-between;
}

.top-part {
  width: 24%;
  height: 100%;
  background-color: #fff;
  border-radius: 8px;
  padding: 10px 20px;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
}

.bottom {
  background-color: #fff;
  width: 100%;
  height: 84%;
  border-radius: 8px;
  padding: 15px;
  position: relative;
}

.topname {
  font-size: 20px;
  font-family: "HarmonyOS_Sans_SC_Medium";
  color: #333;
}

.status-icon {
  width: 10px;
  height: 10px;
  display: inline-block;
  border-radius: 50%;
}

.c-grey {
  background: grey;
}

.c-green {
  background: green;
}

.c-red {
  background: red;
}

.c-yellow {
  background: yellow;
}

.topnum {
  font-size: 14px;
  font-family: "HarmonyOS_Sans_SC_Regular";
  color: #777;
}

.searchLine {
  display: flex;
}

.operatingBtn {
  margin-bottom: 20px;
  margin-top: 20px;
}

.page {
  display: flex;
  height: 80px;
  width: 100%;
  justify-content: center;
  align-items: center;
  box-shadow: 0px -2px 3px 0px rgba(0, 0, 0, 0.02);
  bottom: 0px;
  position: absolute;
}

.pageborder {
  margin-right: 10px;
  border: 1px solid #333;
  width: 35px;
  height: 30px;
  border-radius: 5px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #333;
  font-family: "HarmonyOS_Sans_SC_Regular";
}

.page {
  display: flex;
  height: 50px;
  width: 100%;
  justify-content: center;
  align-items: center;
  box-shadow: 0px -2px 3px 0px rgba(0, 0, 0, 0.02);
  bottom: 10px;
  position: absolute;
}

.pageborder {
  margin-right: 10px;
  border: 1px solid #dcdfe6;
  width: 40px;
  height: 36px;
  border-radius: 5px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #333;
  font-family: "HarmonyOS_Sans_SC_Regular";
}

::v-deep .el-input__inner::-webkit-outer-spin-button,
::v-deep .el-input__inner::-webkit-inner-spin-button {
  -webkit-appearance: none;
}

::v-deep .el-input__inner[type="number"] {
  -moz-appearance: textfield;
}
</style>
